package controllers

import (
	"books/cache"
	"books/models"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Register() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "请输入账号密码",
		}
		c.ServeJSON()
		return
	}

	var user = models.User{
		Username: username,
		Password: password,
	}

	if err := user.GetUserByUsername(); err != nil { //查询用户
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "系统错误",
		}
		c.ServeJSON()
		return
	}

	if user.ID > 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户已存在",
		}
		c.ServeJSON()
		return
	}

	if err := user.Create(); err != nil { //创建用户
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "系统错误",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "success",
	}
	c.ServeJSON()
	return
}

func (c *UserController) Login() {
	
	var err error
	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户名或密码不能为空",
		}
		c.ServeJSON()
		return
	}

	//获取错误次数
	// 如果密码错误，计入错误次数，超过 5 次，封禁 1 小时
	key := "password_error_count" + username
	count, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if count == 4 {
		cache.Rdb.Expire(cache.Ctx, key, time.Hour)
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "密码错误次数过多，封禁 1 小时",
		}
		c.ServeJSON()
		return
	}

	var user = models.User{
		Username: username,
		Password: password,
	}

	if err = user.GetUserByUsername(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "系统错误",
		}
		c.ServeJSON()
		return
	}

	if user.ID == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "用户不存在",
		}
		c.ServeJSON()
		return
	}

	if user.Password != password {
		//错误次数 + 1
		cache.Rdb.Incr(cache.Ctx, key)

		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "密码错误",
		}
		c.ServeJSON()
		return
	}

	cache.Rdb.Del(cache.Ctx, key) //清空错误次数
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "登入成功",
	}
	c.ServeJSON()
	return
}
